package com.blogspot.security.service.impl;

import javax.persistence.NoResultException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blogspot.security.dao.UserDao;
import com.blogspot.security.domain.ApplicationAuthenticatedUser;
import com.blogspot.security.domain.ApplicationUser;

/* 
 * 實做SpringSecurity的UserDetailsService interface
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
	@Autowired
	UserDao userDao;
    /* 
     * 用戶訪問應用資源之前,將會呼叫此方法獲取用戶的登錄資訊及對應的權限範圍(ROLE_USER,ROLE_ADMIN,ROLE_LOGIN)
     */
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
        try {
        	logger.error("Logging usernameloadUserByUsername ");
            ApplicationUser user = userDao.getUser(userName);
            logger.error("Logging usernameloadUserByUsername End");
            if (user != null) {
                logger.error("Logging username:" + user.getUserName());
                return new ApplicationAuthenticatedUser(user);
            } else {
                //log.info("Cant find username or wrong password: " + userName);
            }
        } catch (NoResultException nre) {
            //log.info("Login error:" + nre.getMessage());
        }
        return null;
	}

}
